/**
 * 
 */

package com.shy.portal.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.shy.base.dao.impl.BaseDaoImpl;
import com.shy.base.util.StringUtils;
import com.shy.base.vo.EntityTypeValue;
import com.shy.base.vo.PagerFilter;
import com.shy.base.vo.QueryResult;
import com.shy.portal.dao.UserDao;
import com.shy.portal.entity.Menu;
import com.shy.portal.entity.Permission;
import com.shy.portal.entity.Role;
import com.shy.portal.entity.User;
import com.shy.portal.entity.UserLog;

/**
 * <p>
 * Title: ManagerDaoImpl
 * </p>
 * <p>
 * Description:用户Dao层实现
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author H2013788
 */
@Transactional
@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

    @Override
    public PagerFilter listUserByPager(String whereHql, List<EntityTypeValue> params,
            PagerFilter pagerFilter) {
        Integer firstStart = Integer.parseInt(String.valueOf(pagerFilter.getStart())); // 分页开始下标
        Integer showNum = Integer.parseInt(String.valueOf(pagerFilter.getMax())); // 显示条数
        QueryResult<User> result = this.getScrollDataBindName(firstStart, showNum, whereHql,
                params, pagerFilter.getOrderby());
        if (result != null) {
            pagerFilter.setTotal(result.getTotalrecord());
            pagerFilter.setObjs(result.getResultlist());
        }
        return pagerFilter;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Role> listRoleByUserId(Integer userId) {
        String hql = "FROM  Role WHERE id IN" + " (SELECT DISTINCT role.id FROM "
                + " UserRole WHERE user.id =:userId )" + " ORDER BY id ASC";
        Query query = entityManager.createQuery(hql);
        query.setParameter("userId", userId);
        List<Role> list = query.getResultList();
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Permission> listPermissionByUserId(Integer userId) {
        String hql = "FROM Permission WHERE id IN" + " (SELECT DISTINCT permission.id FROM "
                + " RolePermission WHERE role.id IN" + "  (SELECT role.id FROM "
                + " UserRole WHERE user.id =:userId )" + " )" + " ORDER BY sort ASC";
        Query query = entityManager.createQuery(hql);
        query.setParameter("userId", userId);
        List<Permission> list = query.getResultList();
        return list;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public User getUserByName(String username) {
        String hql = "FROM User WHERE username =:username ";
        Query query = entityManager.createQuery(hql);
        query.setParameter("username", username);
        query.setMaxResults(1);
        List list = query.getResultList();
        return null== list || list.isEmpty() ? null : (User) list.get(0);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Menu> listMenuByUserId(Integer userId) {
        String hql = "FROM Menu WHERE id IN" + " (SELECT DISTINCT menu.id FROM "
                + " RoleMenu WHERE role.id IN" + "  (SELECT role.id FROM "
                + " UserRole WHERE user.id =:userId )" + " )" + " ORDER BY sort ASC";
        Query query = entityManager.createQuery(hql);
        query.setParameter("userId", userId);
        List<Menu> list = query.getResultList();
        return list;
    }

    @SuppressWarnings("unchecked")
	@Override
    public List<User> listUserByParam(String whereHql, List<EntityTypeValue> params) {
        String hql = " FROM  User WHERE 1=1 ";
        if (StringUtils.isNotEmpty(whereHql)) {
            hql = whereHql;
        }
        Query query = entityManager.createQuery(hql);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {
                query.setParameter(params.get(i).getParamName(), params.get(i)
                        .getParamValue());
            }
        }
        return query.getResultList();
    }


    @SuppressWarnings("unchecked")
	@Override
    public PagerFilter listLogByPage(String whereHql, List<EntityTypeValue> params, PagerFilter pagerFilter) {
        Integer firstStart = Integer.parseInt(String.valueOf(pagerFilter.getStart())); // 分页开始下标
        Integer showNum = Integer.parseInt(String.valueOf(pagerFilter.getMax())); // 显示条数
        String hql = " from UserLog where 1=1  ";
        String countHql = " select count(1) from UserLog where 1=1  ";
        if(StringUtils.isNotEmpty(whereHql)){
            hql += " and " + whereHql;
            countHql += " and " + whereHql;
        }
        hql += " order by loginTime desc ";
        Query query = entityManager.createQuery(countHql);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {
                query.setParameter(params.get(i).getParamName(), params.get(i)
                        .getParamValue());
            }
        }
        List<UserLog> list = new ArrayList<>();
        Long total = (Long) query.getSingleResult();;
        if(total > 0){
            query = entityManager.createQuery(hql);
            if (params != null && params.size() > 0) {
                for (int i = 0; i < params.size(); i++) {
                    query.setParameter(params.get(i).getParamName(), params.get(i)
                            .getParamValue());
                }
            }
            query.setFirstResult(firstStart);
            query.setMaxResults(showNum);
            list = query.getResultList();
        }
        pagerFilter.setTotal(total);
        pagerFilter.setObjs(list);
        return pagerFilter;
    }

}
